package proeva;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.java2d.SunGraphicsEnvironment.TTFilter;
import java.sql.*;

/**    
 * Servlet implementation class TryServlet
 */
public class TryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public TryServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String cmd, json="";

		try {
			cmd = request.getParameter("cmd");
		} catch (Exception ex) {
			response.getWriter().write("{success:false, msg:\"Invalid command!\"}");
			return;
		}
		if (cmd.equalsIgnoreCase("list")) {
			StringBuffer data = new StringBuffer("");
			boolean isUDP = false;
			if( request.getParameter("UorS").equalsIgnoreCase("u") )
				isUDP = true;

			if( isUDP )// UDP
			{
				try
				{
					Connection Conn = DBSetting.GetEvaConnection();
					Statement stmt = Conn.createStatement();
					ResultSet result= stmt.executeQuery("SELECT * FROM DDoS_Eva_W WHERE Type='true' ORDER BY Eva_Time DESC");
					while( result.next() )
					{
						data.append("{Eva_Time:\"");
						data.append(result.getTimestamp("Eva_Time"));
						
						data.append("\",Lp:");
						data.append(result.getDouble("Lp"));

						data.append(",Bw:");
						data.append(result.getDouble("Bw"));

						data.append(",Lt:");
						data.append(result.getDouble("Lt"));

						data.append(",Ia:");
						data.append(result.getDouble("Ia"));

						data.append(",Ir:");
						data.append(result.getDouble("Ir"));
						
						data.append(",udpTt:");
						data.append(result.getDouble("udpTt"));

						data.append(",Eva:");
						data.append(result.getDouble("Eva"));

						data.append("},");
					}
					if( data.length() != 0 )
						data.deleteCharAt(data.length() - 1);

					json = "{success:true,msg:\"查询数据库成功\",data:["+data+"]}";
					response.getWriter().write(json);

					result.close();
					stmt.close();
					Conn.close();
				} catch (Exception ex) {
					json = "{success:false,msg:\"查询数据库时出错，请重试"+ex.getMessage()+"\",data:{}}";
					out.write(json);
//					out.write(ex.getMessage());
				}
			}
			else//SYN
			{
				try
				{
					Connection Conn = DBSetting.GetEvaConnection();
					Statement stmt = Conn.createStatement();
					ResultSet result= stmt.executeQuery("SELECT * FROM DDoS_Eva_W WHERE Type='false' ORDER BY Eva_Time DESC");
					while( result.next() )
					{
						data.append("{Eva_Time:\"");
						data.append(result.getTimestamp("Eva_Time"));
						
						data.append("\",Lp:");
						data.append(result.getDouble("Lp"));

						data.append(",Bw:");
						data.append(result.getDouble("Bw"));

						data.append(",M:");
						data.append(result.getInt("M"));

						data.append(",synSa:");
						data.append(result.getDouble("synSa"));

						data.append(",synDelay:");
						data.append(result.getDouble("synDelay"));

						data.append(",Lt:");
						data.append(result.getDouble("Lt"));

						data.append(",Ia:");
						data.append(result.getDouble("Ia"));

						data.append(",Ir:");
						data.append(result.getDouble("Ir"));
						
						data.append(",Ti:");
						data.append(result.getDouble("Ti"));

						data.append(",Eva:");
						data.append(result.getDouble("Eva"));

						data.append("},");
					}
					if( data.length() != 0 )
						data.deleteCharAt(data.length() - 1);

					json = "{success:true,msg:\"查询数据库成功\",data:["+data+"]}";
					response.getWriter().write(json);

					result.close();
					stmt.close();
					Conn.close();
				} catch (Exception ex) {
					json = "{success:false,msg:\"查询数据库时出错，请重试"+ex.getMessage()+"\",data:{}}";
					out.write(json);
				}
			}
		}// if
		else if(cmd.equalsIgnoreCase("save")){
			if( request.getParameter("UorS").equalsIgnoreCase("u"))//udp
			{
				try
				{
					double Lp = Double.parseDouble(request.getParameter("lp"));
					double Bw = Double.parseDouble(request.getParameter("bw"));
					double Lt = Double.parseDouble(request.getParameter("lt"));
					double Ia = Double.parseDouble(request.getParameter("ia"));
					double Ir = Double.parseDouble(request.getParameter("ir"));
					double udpTt = Double.parseDouble(request.getParameter("udptt"));
					double udpE = Double.parseDouble(request.getParameter("eva"));
					
					Connection Conn = DBSetting.GetEvaConnection();
					PreparedStatement pstmt = Conn.prepareStatement("INSERT INTO DDoS_Eva_W ( Type, Eva_Time, Lp, Bw, Lt, Ia, Ir, udpTt, Eva) VALUES (?,?,?,?,?,?,?,?,?)");
					//Eva_Time, Lp, Bw, M, synSa, synDelay, Lt, Ia, Ir, udpTt, udpE
					pstmt.setBoolean(1, true);
					pstmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
					pstmt.setDouble(3, Lp);
					pstmt.setDouble(4, Bw);
					pstmt.setDouble(5, Lt);
					pstmt.setDouble(6, Ia);
					pstmt.setDouble(7, Ir);
					pstmt.setDouble(8, udpTt);
					pstmt.setDouble(9, udpE);
					
					pstmt.execute();
					
					json = "{success:true,msg:\"成功将数据保存到数据库\",data:{}}";
					out.write(json);
					
					pstmt.close();
					Conn.close();
				}
				catch( Exception ex )
				{
					json = "{success:false,msg:\"将数据保存到数据库时出错，请重试"+ex.toString()+"\",data:{}}";
//					json = "{success:false,msg:\"将数据保存到数据库时出错，请重试\",data:{}}";
					out.write(json);
					return;
				}
			}
			else//syn
			{
				try
				{
//					double Lp = Double.parseDouble(request.getParameter("lp"));
//					double Bw = Double.parseDouble(request.getParameter("bw"));
//					double Lt = Double.parseDouble(request.getParameter("lt"));
					//					double udpTt = Double.parseDouble(request.getParameter("udptt"));
					//				//wangbida@gmail.com synflood不需要这几个字段
					
					int M = Integer.parseInt(request.getParameter("m"));
					double synSa = Double.parseDouble(request.getParameter("synsa"));
					double synDelay = Double.parseDouble(request.getParameter("syndelay"));

					double Ia = Double.parseDouble(request.getParameter("ia"));
					double Ir = Double.parseDouble(request.getParameter("ir"));
					double Ti = Double.parseDouble(request.getParameter("ti"));

					double synPb = Double.parseDouble(request.getParameter("synpb"));
					double synE = Double.parseDouble(request.getParameter("eva"));
					
					Connection Conn = DBSetting.GetEvaConnection();
					PreparedStatement pstmt = Conn.prepareStatement("INSERT INTO DDoS_Eva_W ( Type, Eva_Time, M, synSa, synDelay, Ia, Ir, Ti, synPb, Eva) VALUES (?,?,?,?,?,?,?,?,?,?)");
					//Eva_Time, Lp, Bw, M, synSa, synDelay, Lt, Ia, Ir, udpTt, udpE
					pstmt.setBoolean(1, false);
					pstmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
//					pstmt.setDouble(3, Lp);
//					pstmt.setDouble(4, Bw);
					pstmt.setInt(3, M);
					pstmt.setDouble(4, synSa);
					pstmt.setDouble(5, synDelay);
//					pstmt.setDouble(8, Lt);
					pstmt.setDouble(6, Ia);
					pstmt.setDouble(7, Ir);
					pstmt.setDouble(8, Ti);
//					pstmt.setDouble(12, udpTt);
					pstmt.setDouble(9, synPb);
					pstmt.setDouble(10, synE);
					
					pstmt.execute();
					
					json = "{success:true,msg:\"成功将数据保存到数据库\",data:{}}";
					out.write(json);
					
					pstmt.close();
					Conn.close();
				}
				catch( Exception ex )
				{
					json = "{success:false,msg:\"将数据保存到数据库时出错，请重试"+ex.getMessage()+"\",data:{}}";
					out.write(json);
					return;
				}
			}
		}
		else if(cmd.equalsIgnoreCase("calc")){
			if( request.getParameter("UorS").equalsIgnoreCase("u") )
			{
				try {
					double Lp = Double.parseDouble(request.getParameter("lp"));
					double Bw = Double.parseDouble(request.getParameter("bw"));
					double Lt = Double.parseDouble(request.getParameter("lt"));
					double Ir = Double.parseDouble(request.getParameter("ir"));
					double Ia = Double.parseDouble(request.getParameter("ia"));

					DDoS_W ddosW = new DDoS_W();
					double udpT = ddosW.udpCalcT(Lp, Bw,Ir,Ia);
					double udpTt = udpT*Lt*1000000/Lp;
					String udpE = Double.toString(ddosW.calcE(udpTt, 0,0));
					json = "{success:true,msg:\"计算成功\",data:{eva:" + udpE +"}}";

				} catch (Exception e) {
					// TODO Auto-generated catch block
					json = "{success:false,msg:\"提交的参数不完整!\n需要：lp, bw, lt, ir, ia\",data:{}}";
				} finally{
					response.getWriter().write(json);
				}
			}
			else//syn
			{
				try
				{
					int M = Integer.parseInt(request.getParameter("m"));
					double Sa = Double.parseDouble(request.getParameter("sa"));
					double Sr = Double.parseDouble(request.getParameter("sr"));
					double Ir = Double.parseDouble(request.getParameter("ir"));
					double Ia = Double.parseDouble(request.getParameter("ia"));
					double Lp = Double.parseDouble(request.getParameter("lp"));
					double Bw = Double.parseDouble(request.getParameter("bw"));
					double Lt = Double.parseDouble(request.getParameter("lt"));
					double Ti = Double.parseDouble(request.getParameter("ti"));
					
					DDoS_W ddosW = new DDoS_W();
					double synPb = ddosW.synCalcPb(M, Sa, Sr, Ir, Ia);
					double udpT = ddosW.udpCalcT(Lp, Bw,Ir,Ia);
					double udpTt = udpT*Lt*1000000/Lp;
					double udpE = ddosW.calcE(udpTt, synPb, Ti);
					json = "{success:true,msg:\"计算成功\",data:{eva:"+ udpE +"}}";
				}
				catch( Exception ex )
				{
					json = "{success:false,msg:\"提交的参数不完整！\",data:{}}";
				}
				finally
				{
					response.getWriter().write(json);
				}
			}

		}
		else{
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			return;
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet( request, response );
	}

}
